import streamlit as st
import pandas as pd
import streamlit.components.v1 as components
from jinja2 import Template
import os
import re
import time
import jieba
import pdfplumber
import warnings
import logging
import base64
from st_aggrid import AgGrid, GridOptionsBuilder


# 页面美化：苹果风格极简设计
st.set_page_config(page_title="公司信息查询系统", layout="wide")

# 引入外部CSS
with open("style/custom.css", "r", encoding="utf-8") as f:
    st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

# 搜索框状态管理
if 'searchbox' not in st.session_state:
    st.session_state['searchbox'] = ''

# 在渲染输入框前处理pending_searchbox
if 'pending_searchbox' in st.session_state:
    st.session_state['searchbox'] = st.session_state['pending_searchbox']
    del st.session_state['pending_searchbox']

# 读取数据
@st.cache_data(ttl=300)  # 缓存5分钟
def load_data():
    try:
        with st.spinner("正在加载数据..."):
            df = pd.read_excel("new.xlsx")  # 读取所有列
        return df
    except Exception as e:
        st.error(f"数据加载失败：{e}")
        return pd.DataFrame()

# 添加刷新数据的函数
def refresh_data():
    st.cache_data.clear()
    return load_data()

df = load_data()

# 内容卡片区
st.markdown('<div class="apple-title">公司数字化信息查询系统</div>', unsafe_allow_html=True)
st.markdown('<div class="apple-subtitle">极简设计 · 极速检索 </div>', unsafe_allow_html=True)

# 简单搜索框
st.markdown('<div class="simple-search-container">', unsafe_allow_html=True)
search_input = st.text_input(
    "搜索企业",  # 非空label，隐藏
    key="searchbox",
    placeholder="例如:北京大豪科技股份有限公司",
    label_visibility="collapsed"
)
st.markdown('</div>', unsafe_allow_html=True)

# 模糊搜索和下拉建议功能
search_input = st.session_state.get('searchbox', '')

# 生成搜索建议
def get_search_suggestions(query, df, max_suggestions=10):
    if not query:
        return []
    
    suggestions = []
    query_lower = query.lower()
    
    # 搜索股票代码
    code_matches = df[df["股票代码"].astype(str).str.contains(query, case=False, na=False)]
    for _, row in code_matches.head(5).iterrows():
        suggestions.append(f"{row['股票代码']} - {row['企业名称']}")
    
    # 搜索企业名称
    name_matches = df[df["企业名称"].str.contains(query, case=False, na=False)]
    for _, row in name_matches.head(5).iterrows():
        suggestion = f"{row['股票代码']} - {row['企业名称']}"
        if suggestion not in suggestions:
            suggestions.append(suggestion)
    
    return suggestions[:max_suggestions]

# 显示搜索建议
if search_input:
    suggestions = get_search_suggestions(search_input, df)
    if suggestions and len(suggestions) > 0:
        st.markdown('<div class="suggestions-title">💡 搜索建议：</div>', unsafe_allow_html=True)
        for i, suggestion in enumerate(suggestions):
            if st.button(f"📋 {suggestion}", key=f"suggestion_{i}", help="点击选择此选项"):
                if " - " in suggestion:
                    selected_text = suggestion.split(" - ")[1]
                else:
                    selected_text = suggestion
                st.session_state['pending_searchbox'] = selected_text
                st.experimental_rerun()

# 查询逻辑
if search_input:
    result = df[
        df["股票代码"].astype(str).str.contains(search_input, case=False, na=False) |
        df["企业名称"].str.contains(search_input, case=False, na=False)
    ]
    if len(result) > 0:
        st.success(f"找到 {len(result)} 条匹配记录")
    else:
        st.warning("未找到匹配的记录")
else:
    # 当用户没有输入时，显示所有数据
    result = df

# 数据统计极简卡片
st.markdown('<div style="text-align:center; margin-top:2em;">', unsafe_allow_html=True)
st.info(f"总记录数：{len(df)}", icon="📊")

# 分页功能
page_size = 10  # 每页显示10个企业
total = len(result)
total_pages = (total - 1) // page_size + 1

# 初始化
if 'current_page' not in st.session_state:
    st.session_state['current_page'] = 1

# 读取URL参数并同步
params = st.query_params
if "page" in params:
    try:
        page = int(params["page"])
        if 1 <= page <= total_pages:
            st.session_state['current_page'] = page
    except:
        pass

current_page = st.session_state['current_page']

# 获取当前页数据
start_idx = (current_page - 1) * page_size
end_idx = min(start_idx + page_size, total)
current_page_data = result.iloc[start_idx:end_idx]

# 股票代码补零
if '股票代码' in current_page_data.columns:
    current_page_data['股票代码'] = current_page_data['股票代码'].astype(str).str.zfill(6)

# 按钮和说明在表格上方一行
row1_col1, _ = st.columns([1, 1])
with row1_col1:
    if st.button("上传年报", help="支持批量上传多个PDF年报文件，解析提取数字化指数"):
        st.session_state['show_upload'] = True


if st.session_state.get('show_upload', False):
    uploaded_files = st.file_uploader(
        "", type=["pdf"], label_visibility="collapsed", key="pdf_upload", accept_multiple_files=True)
    if uploaded_files is not None and len(uploaded_files) > 0:
        # 创建统一的进度条
        total_files = len(uploaded_files)
        progress_bar = st.progress(0, text=f"正在批量解析 {total_files} 个文件...")
        
        # 批量处理文件
        for file_index, uploaded_file in enumerate(uploaded_files):
            filename = uploaded_file.name
            is_pdf = filename.lower().endswith('.pdf')
            code_match = re.search(r'\d{6}', filename)
            name_match = '公司' in filename
            if not is_pdf or (not code_match and not name_match):
                continue  # 跳过不合规文件
            save_path = os.path.join("pdfData", filename)
            with open(save_path, "wb") as f:
                f.write(uploaded_file.getbuffer())
            # 只更新进度条
            current_progress = file_index / total_files
            progress_bar.progress(current_progress, text=f"完成第 {file_index}/{total_files} 个文件的解析, 正在解析中……")
            import time
            time.sleep(0.1)
            try:
                # 维度与关键词
                dimensions = {
                    '人工智能技术': ['人工智能', '图像理解', '智能数据分析', '智能机器人',
                                '机器学习', '深度学习', '语义搜索', '语言识别', '身份验证', '自动驾驶',
                                '自然语言处理', '神经网络', '卷积神经'],
                    '区块链技术': ['区块链', '分布式记账', '数字货币', '差分隐私技术', '智能金融合约', '加密货币'],
                    '大数据技术': ['大数据', '数据挖掘', '文本挖掘', '数据可视化', '异构数据', '增强现实',
                                  '混合现实', '虚拟现实', '图像识别', '机器视觉', '雷达点云'],
                    '云计算技术': ['云计算', '流计算', '图计算', '内存计算', '安全计算',
                                  '类脑计算认知计算', '融合架构', 'EB级存储', '物联网', '信息物理系统', '机器通信'],
                    '数字技术应用': ['移动互联网', '人工互联网', '无人工厂', '互联网医疗', '电子商务', '移动支付',
                                    '第三方支付', 'NFC支付', '智能能源', 'B2B', 'B2C', 'C2B', 'C2C', 'O2O',
                                    '智能穿戴', '智慧农业', '智能交通', '智慧医疗', '智慧客服', '智能家居',
                                    '智能文旅', '智能环保', '智能电网', '智慧营销', '数字销售', '无人零售',
                                    '互联网金融', '数字金融', 'Fintech', '金融科技', '量化金融', '开放银行']
                }
                # 提取股票代码
                stock_code = code_match.group(0) if code_match else ''
                stock_code = stock_code.zfill(6)  # 补齐6位
                # 解析PDF
                with pdfplumber.open(save_path) as pdf:
                    text = ""
                    for page in pdf.pages:
                        text += page.extract_text() if page.extract_text() else ""
                    # 企业名正则
                    company_name_pattern = re.compile(r'([\u4e00-\u9fa5a-zA-Z()（）\s]+公司)')
                    match = company_name_pattern.search(text[:1000])
                    company_name = match.group(1) if match else '未找到企业名'
                    words = jieba.lcut(text)
                    row = {dim: 0 for dim in dimensions.keys()}
                    total_keywords = 0
                    for dimension, keywords in dimensions.items():
                        for keyword in keywords:
                            count = words.count(keyword)
                            row[dimension] += count
                            total_keywords += count
                    row['总词频数'] = total_keywords
                    row['企业名称'] = company_name
                # 追加到new.xlsx
                if os.path.exists("new.xlsx"):
                    df = pd.read_excel("new.xlsx")
                else:
                    df = pd.DataFrame()
                # 构造新行
                new_row = {
                    '股票代码': stock_code,
                    '企业名称': row['企业名称'],
                    '数字技术应用': row['数字技术应用'],
                    '人工智能技术': row['人工智能技术'],
                    '区块链技术': row['区块链技术'],
                    '大数据技术': row['大数据技术'],
                    '云计算技术': row['云计算技术'],
                    '总词频数': row['总词频数']
                }
                # 检查企业名称是否已存在
                exists = False
                if not df.empty and new_row['企业名称'] in df['企业名称'].values:
                    exists = True
                # 删除企业名称相同的行
                df = df[df['企业名称'] != new_row['企业名称']]
                # 追加新行
                df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
                df['股票代码'] = df['股票代码'].astype(str).str.zfill(6)  # 写入前补零
                df.to_excel("new.xlsx", index=False)
            except Exception as e:
                pass
        # 处理完成后，进度条100%
        progress_bar.progress(1.0, text=f"批量解析完成！共处理 {total_files} 个文件")
        time.sleep(1)
        
        # 自动刷新数据
        st.success(f"✅ 年报解析完成！共处理 {total_files} 个文件，数据已自动更新")
        
        # 清除缓存并重新加载数据
        st.cache_data.clear()
        df = refresh_data()
        
        # 重置上传状态
        st.session_state['show_upload'] = False
        
        # 强制刷新页面
        st.experimental_rerun()

# 表格显示
st.dataframe(current_page_data, use_container_width=True, height=400)

# 页码文本紧贴表格底部并居中
st.markdown(
    f'''<div style="width:100%;text-align:center;font-size:13px;font-weight:500;background:#f8f9fa;border-radius:6px;border:1.5px solid #e9ecef;padding:0 24px;min-width:180px;height:28px;display:flex;align-items:center;justify-content:center;color:#333;margin:0 auto 0 auto;">第 {current_page} 页 / 共 {total_pages} 页</div>''',
    unsafe_allow_html=True
)

# 分页按钮（在页码信息下方）
if total_pages > 1:
    st.markdown("""
    <style>
    .pager-btn-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 0;
        margin-bottom: 0;
        padding: 0 8vw 0 8vw;
    }
    .pager-btn-row .stButton > button {
        height: 28px !important;
        min-width: 36px !important;
        font-size: 13px !important;
        background: #f8f9fa !important;
        color: #333 !important;
        border: 1.5px solid #b2bec3 !important;
        border-radius: 6px !important;
        padding: 0 12px !important;
        box-shadow: none !important;
        margin: 0 !important;
    }
    .pager-btn-row .stButton > button:disabled {
        background: #f1f2f6 !important;
        color: #b2bec3 !important;
        border: 1.5px solid #dfe4ea !important;
        opacity: 0.7 !important;
    }
    </style>
    """, unsafe_allow_html=True)

    st.markdown('<div class="pager-btn-row">', unsafe_allow_html=True)
    col_left,_, j, i, col_right = st.columns([1,2,3,2,1])
    with col_left:
        prev_disabled = current_page <= 1
        if st.button("◀", key="prev_page", disabled=prev_disabled):
            st.session_state['current_page'] = max(1, current_page - 1)
            st.experimental_rerun()
    with col_right:
        next_disabled = current_page >= total_pages
        st.markdown('<div style="display:flex;justify-content:flex-end;">', unsafe_allow_html=True)
        if st.button("▶", key="next_page", disabled=next_disabled):
            st.session_state['current_page'] = min(total_pages, current_page + 1)
            st.experimental_rerun()
        st.markdown('</div>', unsafe_allow_html=True)
    st.markdown('</div>', unsafe_allow_html=True)

    

# 底部极简灰色小字
st.markdown("""
<div style='text-align:center; color: #b2bec3; font-size:0.95em; margin-top:32px;'>
© 2025 公司数字化信息查询系统 | 联系方式：1141194854@qq.com
</div>
""", unsafe_allow_html=True)

st.markdown(
    """
    <style>
    .stApp, .block-container, .main {
        background: linear-gradient(135deg, #e0eafc 0%, #cfdef3 90%) !important;
        min-height: 100vh;
    }
    </style>
    """,
    unsafe_allow_html=True
)


